home *** CD-ROM | disk | FTP | other *** search
/ CGI How-To / CGI HOW-TO.iso / chap2 / 2_9 / chk-acpt.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-06-15  |  1.9 KB  |  81 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. /* function prototype */
  6. int DumpFile(char* filename, char* content_type);
  7.  
  8. main()
  9. {
  10.     char* http_accept = getenv("HTTP_ACCEPT");
  11.  
  12.     if (http_accept != NULL)
  13.     {
  14.         if (strstr(http_accept, "image/jpeg"))
  15.         {
  16.             /* Browser understands JPEGs so show a JPEG image */
  17.             DumpFile("lighthou.jpg", "image/jpeg");
  18.             exit(0);     /* exit the program */
  19.         }
  20.         else if (strstr(http_accept, "image/gif"))
  21.         {
  22.             /* Browser understands GIFs so show a GIF image */
  23.             DumpFile("lighthou.gif", "image/gif");
  24.             exit(0);     /* exit the program */
  25.       }
  26.     }
  27.  
  28.     /* If we get to this point then either the HTTP_ACCEPT variable was not set
  29.      * or the accept type was not found in the tests above. Therefore the
  30.      * browser cannot support GIFs or JPEGs so we show some text.
  31.      */
  32.  
  33.     printf("Content-type: text/plain\n\n");
  34.     printf("Text is the only thing I can show you.\n");
  35.     printf("Hope you weren't expecting an image or something.\n");
  36.     exit(0);
  37. }
  38.  
  39.  
  40. /* function DumpFile()
  41.  *
  42.  * Opens a input file specified by the variable filename and dumps the
  43.  * contents to stdout in 8K chunks. An error is displayed if the file cannot
  44.  * be opened.
  45.  *
  46.  * Returns: 0 if successful,
  47.  *          1 if failed (cannot open file).
  48.  */
  49.  
  50. int DumpFile(char* filename, char* content_type)
  51. {
  52.     FILE *fp = fopen(filename, "r");
  53.     if (fp == NULL)
  54.     {
  55.         printf("Content-type: text/plain\n\n");
  56.         /* We have a problem so call the webmaster for help */
  57.         printf("Sorry, the file '%s' cannot be opened.\n", filename);
  58.         printf("Please report this error to the webmaster.\n");
  59.         return(1);
  60.     }
  61.     else
  62.     {
  63.         char buf[8096];
  64.         int nread;
  65.         printf("Content-type: %s\n\n", content_type);
  66.         /* Read and output file in 8K chunks at a time which is faster
  67.          * than doing so one byte at a time.
  68.          */
  69.         while ((nread = fread(buf, 1, sizeof(buf), fp)) != 0)
  70.         {
  71.             fwrite(buf, 1, nread, stdout); /* write buffer to stdout */
  72.        }
  73.         fclose(fp);
  74.         return(0);
  75.     }    
  76. }
  77.  
  78. /*
  79.  * end of chk-acpt.c
  80.  */
  81.